<?php

namespace app\exception\Adapter;

use app\cms\model\themeModel;
use app\cms\tags\config;
use iflow\App;
use iflow\Container\implement\annotation\tools\data\Inject;
use iflow\exception\Annotation\ConfigureException;
use iflow\exception\ExceptionConfigureInterface;
use iflow\Response;
use iflow\Router\implement\exception\RouterNotFoundException;

#[ConfigureException(RouterNotFoundException::class)]
class ResponseNotFoundException implements ExceptionConfigureInterface {

    #[Inject]
    protected config $config;

    #[Inject]
    protected themeModel $themeModel;

    public function configure(\Throwable $throwable, App $app, \Closure $next, array $args = []): mixed {
        // TODO: Implement configure() method.

        $config = (new config()) -> getConfig();
        if (!$config || $config['status'] === 0) return $next($app);

        $host = request() -> getHeader('host');
        // 获取域名指定主题
        $theme = $this->themeModel -> getThemeByDomain($host);

        // 当无指定主题时获取配置默认主题
        if ($theme === null) {
            $theme = $this->themeModel -> where([
                'site_theme_id' => $config['site_theme_id']
            ]) -> findOrEmpty();
            $theme = $theme -> isExists() ? $theme -> toArray() : null;
        }

        // 获取主题后 且主题存在
        if ($theme !== null) {
            return $this->getThemeFile($theme, $config) ?: $next($app);
        }

        return $next($app);
    }

    /**
     * 获取主题响应文件
     * @param array $theme
     * @param array $config
     * @return Response|null
     */
    public function getThemeFile(array $theme, array $config): ?Response {

        $template = config('template');
        $request_uri = trim(request() -> request_uri, '/');

        if ($request_uri === '') {
            $request_uri = 'index';
        }

        $path = $template['view_root_path'].trim($request_uri, '/'). ".${template['view_suffix']}";

        // 验证视图文件是否存在
        if (!file_exists($path)) return null;
        return view("theme/{$theme['site_theme_uuid']}/html/${request_uri}", array_merge([
            'config' => $config
        ], request() -> params()));
    }

    /**
     * @param string $uri 访问地址
     * @param int $themeId 关联主题ID
     * @return Response|null
     */
    public function getThemeLayoutsFile(string $uri, int $themeId): ?Response {

    }

}
